import { Component, OnInit } from '@angular/core';
import {UtilService} from './my-service/util.service';
import {Store,Select} from '@ngxs/store';
import {getUserGuid} from './app.state';
import {SetUser,NavState,SetBackground,BackgroundState,BackgroundVariedState,SetBackgroundVaried} from './app.state';
import {RollService} from './my-service/roll.service';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  @Select(NavState) nav$:Observable<any>; //获取当前导航条信息
  @Select(BackgroundState) background$:Observable<any>; //获取背景颜色信息
  @Select(BackgroundVariedState) isVaried$:Observable<any>; //背景颜色是否开启渐变
  backGround='#fff';
  isVaried=false;// 是否渐变
  colors = [
    [204, 204, 51],
    [175, 222, 80],
    [133, 238, 98],
    [91, 244, 145],
    [107, 201, 252]
  ];//颜色二维数组
  colorIndex = 0;
  setIntervalID = null; //定时器Id
  setIntervalBgc=null; //定时器返回的颜色
  constructor(
    private store: Store,
    private utilService: UtilService,
    private rollService:RollService
  ) {
    this.nav$.subscribe(res=>{
      if(res!=='index'){
          //同时停止变色
        this.store.dispatch(new SetBackground('#fff','#00cccc'));
        window.clearInterval(this.setIntervalID);
        }else {
         //开启变色
        this.setIntervalID= setInterval(() => {
          this.setIntervalBgc = this.changeColor();
          this.store.dispatch(new SetBackground(this.setIntervalBgc,this.setIntervalBgc));
        }, 6000)
      }
    });
    // 获取背景颜色
    this.background$.subscribe(res=>{
      this.backGround = res.indexBackground;
    });
    this.isVaried$.subscribe(res=>{
      this.isVaried=res;
    });
  }
  ngOnInit () {
    // 获取用户信息
    this.utilService.getUserInfo().then(res=>{
      if(res.status==1){
          let userGuid = res.userGuid;
          this.store.dispatch(new getUserGuid(userGuid,true));
          this.rollService.getUserInfo(userGuid).then(res=>{
            if(res.status==1){
              let user = res.data;
              let HeadPhotoPath=user.HeadPhotoPath;
              if(HeadPhotoPath){
                  HeadPhotoPath=this.utilService.readImgUrl+HeadPhotoPath;
              }else {
                  HeadPhotoPath='/assets/img/touxiang.png';
              }
              this.store.dispatch(new SetUser(user.Name,user.NickName,HeadPhotoPath,user.Email,user.Phone,user.Sex,user.School));
            }
          })
      }else {
        this.store.dispatch(new getUserGuid(null,false));
      }
    })
  }
  //背景变色
  changeColor() {
    this.colorIndex += 1;
    if (this.colorIndex == this.colors.length) {
      this.colorIndex = 0;
    }
    let colorHex = this.colors[this.colorIndex][0].toString(16) + this.colors[this.colorIndex][1].toString(16) + this.colors[this.colorIndex][2].toString(16);
    return  "#" + colorHex;
  }

}
